package com.kedsoft.andaily.api;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.kedsoft.andaily.common.CommonResult;
import com.kedsoft.andaily.entity.*;
import com.kedsoft.andaily.service.*;
import com.kedsoft.andaily.service.impl.JpushService;
import com.kedsoft.andaily.util.DateUtil;
import com.kedsoft.andaily.vo.ListVo;
import com.kedsoft.andaily.vo.PageVo;
import com.kedsoft.andaily.vo.Pagination;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/******************************************************************
 * @文件名称 : TaskApiController
 * @文件作者 : 卢素强
 * @创建时间 : 2019/4/25 13:36
 * @文件描述 : 
 * @修改历史 : 2019/4/25
 ******************************************************************/
@Api("任务管理")
@RestController
@RequestMapping(value = "/api/task")
public class TaskApiController {
    @Autowired
    TaskService taskService;

    @Autowired
    TaskFileService taskFileService;

    @Autowired
    CunsumerService cunsumerService;

    @Autowired
    LogsService logsService;

    @Autowired
    ParamService paramService;

    @Autowired
    JpushService jpushService;

    @ApiOperation(value = "我的任务列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "page", dataType = "int",defaultValue = "1", required = true, value = "第几页"),
            @ApiImplicitParam(paramType = "query", name = "rows", dataType = "int",defaultValue = "20", required = true, value = "行数"),
            @ApiImplicitParam(paramType = "query", name = "sort", dataType = "String", defaultValue = "id", required = false, value = "排序主键"),
            @ApiImplicitParam(paramType = "query", name = "order", defaultValue = "asc", dataType = "String", required = false, value = "排序"),
            @ApiImplicitParam(paramType = "query", name = "startTime", dataType = "String", required = false, value = "完成-开始时间"),
            @ApiImplicitParam(paramType = "query", name = "endTime", dataType = "String", required = false, value = "完成-结束时间"),
            @ApiImplicitParam(paramType = "query", name = "minAssess", dataType = "int", required = false, value = "评分-大于"),
            @ApiImplicitParam(paramType = "query", name = "maxAssess", dataType = "int", required = false, value = "评分-小于"),
            @ApiImplicitParam(paramType = "query", name = "taskType", dataType = "int", required = false, value = "任务类型,0:派单任务，1：日常任务，2：延期未执行任务，3：计划任务"),
            @ApiImplicitParam(paramType = "query", name = "status", dataType = "int", required = false, value = "状态 0:未完成 1:已完成")
    })
    @RequestMapping(value = "pageList", method = RequestMethod.GET)
    public CommonResult<PageVo<Task>> getPageList(@CookieValue("userName") String userName, Pagination pagination,
                                                  @RequestParam(required = false) String startTime, @RequestParam(required = false) String endTime,
                                                  @RequestParam(required = false) Integer minAssess, @RequestParam(required = false) Integer maxAssess,
                                                  @RequestParam int status, @RequestParam(required = false) Integer taskType)
    {
        Cunsumer cunsumer = cunsumerService.getCunsumerByMobile(userName);

        EntityWrapper<Task> entityWrapper = new EntityWrapper<>();
        //管理员2，查询所有
        if(cunsumer.getLeader() == 1)
        {
            //组长
            entityWrapper.eq("cunsumerid",cunsumer.getId());
        }
        else if(cunsumer.getLeader() == 0){
            entityWrapper.eq("cid",cunsumer.getId());
        }

        if(!org.thymeleaf.util.StringUtils.isEmpty(startTime))
        {
            entityWrapper.ge("stoptime", startTime);
        }
        if(!org.thymeleaf.util.StringUtils.isEmpty(endTime))
        {
            entityWrapper.le("stoptime", endTime);
        }
        if(status == 0)
        {
            //未完成
            entityWrapper.lt("status", 40);
            if(taskType == 0)
            {
                entityWrapper.ge("createtime", DateUtil.format(new Date()) + " 00:00:00");
                entityWrapper.le("createtime", DateUtil.format(new Date()) + " 23:59:59");
//                entityWrapper.in("tasktype", "10,20,30,90");//派单任务
                entityWrapper.notIn("tasktype","40,50,60,70,80");
            }
            else if(taskType == 1){
                entityWrapper.ge("createtime", DateUtil.format(new Date()) + " 00:00:00");
                entityWrapper.le("createtime", DateUtil.format(new Date()) + " 23:59:59");
                entityWrapper.in("tasktype", "40,50,60,70,80");//日常任务
            }
            else if(taskType == 2){
                entityWrapper.le("createtime", DateUtil.format(new Date()) + " 00:00:00");
//                entityWrapper.in("tasktype", "40,50,60,70,80");//日常任务
            }
            else if(taskType == 3){
                entityWrapper.ge("createtime", DateUtil.format(new Date()) + " 23:59:59");
//                entityWrapper.in("tasktype", "40,50,60,70,80");//日常任务
            }
        }
        else {
            //已完成
            entityWrapper.ge("status", 40);

            if(minAssess != null)
            {
                entityWrapper.ge("assess", minAssess);
            }
            if(maxAssess != null)
            {
                entityWrapper.le("assess", maxAssess);
            }
        }

        if(pagination.getOrder()!=null) {
            if (pagination.getOrder().toLowerCase().equals("asc")){
                entityWrapper.orderBy(pagination.getSort(), true);
            }else{
                entityWrapper.orderBy(pagination.getSort(), false);
            }
        }
        Page<Task> page = new Page<>(pagination.getPage()==null?1:pagination.getPage(),
                pagination.getRows()==null?20:pagination.getRows());

        taskService.selectPage(page,entityWrapper);
        PageVo<Task> pageVo = new PageVo<>(page.getRecords(),page.getTotal());
        return CommonResult.success(pageVo);
    }

    @ApiOperation(value = "获取任务")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "taskId", dataType = "int", required = true, value = "任务ID"),
    })
    @RequestMapping(value = "form", method = RequestMethod.GET)
    public CommonResult<HashMap> getTask(@RequestParam("taskId") int taskId)
    {
        //查询任务
        Task task = taskService.selectById(taskId);

        EntityWrapper<TaskFile> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("taskid",taskId);
        List<TaskFile> files = taskFileService.selectList(entityWrapper);

        HashMap<String, Object> map = new HashMap<>(2);
        map.put("task", task);
        map.put("taskFiles", files);
        return CommonResult.success(map);
    }

    @ApiOperation(value = "重新派单")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "taskId", dataType = "int", required = true, value = "任务ID"),
            @ApiImplicitParam(paramType = "query", name = "cid", dataType = "int", required = true, value = "接单人员ID"),
    })
    @RequestMapping(value = "reSendTask", method = RequestMethod.GET)
    public CommonResult<Task> reSendTask(@RequestParam("taskId") int taskId, @RequestParam("cid") int cid)
    {
        Cunsumer cunsumer = cunsumerService.selectById(cid);
        Task task = new Task();
        task.setId(taskId);
        task.setCreatetime(new Date());
        task.setStatus(10);//派单
        task.setCid(cunsumer.getId());
        task.setCname(cunsumer.getName());
        task.setCmobile(cunsumer.getMobile());

        taskService.updateById(task);

        //查询任务
        Task bean = taskService.selectById(taskId);
        logsSave(bean,"被","派单");

        //推送到Android客户端
        Map<String, String> extrasMap = new HashMap<String, String>();
        String title = bean.getBoardname()+"("+bean.getTasktypestr()+")";
        String content = "任务："+title+"["+ DateUtil.format(bean.getCreatetime(),"yyyy年MM月dd日 HH时mm分ss秒")+"],联系人："+bean.getJbname()+"电话："+bean.getJbphone();
        jpushService.sendCustomPush(title,content,extrasMap,bean.getCmobile());

        return CommonResult.success(bean);
    }

    @ApiOperation(value = "接单")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "taskId", dataType = "int", required = true, value = "任务ID"),
    })
    @RequestMapping(value = "acceptTask", method = RequestMethod.GET)
    public CommonResult<Task> acceptTask(@RequestParam("taskId") int taskId)
    {
        Task task = new Task();
        task.setId(taskId);
        task.setGettime(new Date());
        task.setStatus(20);//接单
        taskService.updateById(task);
        //查询任务
        Task bean = taskService.selectById(taskId);
        logsSave(bean,"被","接单");

        return CommonResult.success(bean);
    }

    @ApiOperation(value = "开始执行任务")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "taskId", dataType = "int", required = true, value = "任务ID"),
    })
    @RequestMapping(value = "startTask", method = RequestMethod.GET)
    public CommonResult<Task> startTask(@RequestParam("taskId") int taskId)
    {
        Task task = new Task();
        task.setId(taskId);
        task.setOptime(new Date());
        task.setStatus(30);//执行中
        taskService.updateById(task);
        //查询任务
        Task bean = taskService.selectById(taskId);
        logsSave(bean,"被","执行");

        return CommonResult.success(bean);
    }

    @ApiOperation(value = "保存任务")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", dataType = "int", required = true, value = "任务ID"),
            @ApiImplicitParam(paramType = "query", name = "tasktype", dataType = "int", required = true, value = "任务类型"),
            @ApiImplicitParam(paramType = "query", name = "csum", dataType = "int", required = true, value = "现场操作人员数量"),
            @ApiImplicitParam(paramType = "query", name = "content", dataType = "String", required = true, value = "现场描述"),
            @ApiImplicitParam(paramType = "query", name = "working", dataType = "String", required = true, value = "操作描述"),
            @ApiImplicitParam(paramType = "query", name = "status", dataType = "int", required = true, value = "状态（30：执行中，40：结单）")
    })
    @RequestMapping(value = "saveTask", method = RequestMethod.POST)
    public CommonResult<Task> stopTask(Task task)
    {
        task.setStoptime(new Date());
//        task.setStatus(40);//结单
        task.setTasktypestr(getParam(task.getTasktype()).getTitle());
        taskService.updateById(task);
        //查询任务
        Task bean = taskService.selectById(task.getId());

        if(task.getStatus() == 40)
        logsSave(bean,"被","结单");

        return CommonResult.success(bean);
    }

    @ApiOperation(value = "取消任务")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "taskId", dataType = "int", required = true, value = "任务ID"),
            @ApiImplicitParam(paramType = "query", name = "reason", dataType = "String", required = false, value = "取消原因"),
    })
    @RequestMapping(value = "cancelTask", method = RequestMethod.GET)
    public CommonResult<Task> cancelTask(@RequestParam("taskId") int taskId, @RequestParam("reason") String reason)
    {
        Task task = taskService.selectById(taskId);
        logsSave(task,"被","取消，原因："+ reason);

        task.setGettime(null);
        task.setOptime(null);
        task.setStatus(10);//派单
        task.setCsum(0);
        task.setContent("");
        task.setWorkimg("");
        task.setCid(task.getCunsumerid());
        task.setCname(task.getCunsumername());
        task.setCmobile(task.getCunsumermobile());

        taskService.updateById(task);

        EntityWrapper<TaskFile> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("taskid",taskId);
        taskFileService.delete(entityWrapper);

        return CommonResult.success(task);
    }

    /**
     * 运维类型查询
     * @param tasktype
     * @return
     */
    private Param getParam(Integer tasktype){
        EntityWrapper<Param> query = new EntityWrapper<>();
        query.eq("groups","运维类型");
        query.eq("value",tasktype);
        Param p = paramService.selectOne(query);
        return p;
    }

    /**
     *
     * @param bean
     * @param opv 操作动词
     * @param opresult 操作结果
     */
    private void logsSave(Task bean,String opv, String opresult){
        //任务类型名称
        Param p = getParam(bean.getTasktype());
        String opvalue = "[("+bean.getId()+")"+bean.getBoardname()+"]:【"+p.getTitle()+"】任务 "+opv+bean.getCunsumername()+"("+bean.getCunsumermobile()+")"+opresult+"。";
        //创建日志
        Logs logs = new Logs(bean.getId(),bean.getBoardname(),opvalue,new Date(),bean.getCunsumername());
        logsService.insert(logs);
    }

    @ApiOperation(value = "获取参数")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "groups", dataType = "String", required = true, value = "参数类型"),
    })
    @RequestMapping(value = "paramlist", method = RequestMethod.GET)
    public CommonResult<List<Param>> getParamList(@RequestParam("groups")String groups)
    {
        EntityWrapper<Param> query = new EntityWrapper<>();
        query.eq("groups", groups);
        return CommonResult.success(paramService.selectList(query));
    }

    @ApiOperation(value = "获取巡检单位任务统计")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "routerId", dataType = "int", required = true, value = "巡视单位ID"),
            @ApiImplicitParam(paramType = "query", name = "yearMonth", dataType = "String", required = true, value = "年月：yyyy-MM"),
    })
    @RequestMapping(value = "routerTaskCountList", method = RequestMethod.GET)
    public CommonResult<ListVo<Map<String,Object>>> getRouterTaskCountList(@RequestParam("routerId") Integer id, @RequestParam("yearMonth") String yearMonth)
    {
        ListVo<Map<String,Object>> listVo = new ListVo(taskService.selectRouterTaskCountList(id, yearMonth));
        return CommonResult.success(listVo);
    }
}
